package juc.utils.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreExample3 {
    public static void main(String[] args) throws InterruptedException {
        final Semaphore semaphore = new Semaphore(1);

        Thread t1 = new Thread() {
            @Override
            public void run() {
                try {
                    semaphore.acquire();
                    TimeUnit.SECONDS.sleep(4);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
                System.out.println("t1 finished");
            }
        };
        t1.start();
        //确保第一个线程比第二个线程先启动
        TimeUnit.MILLISECONDS.sleep(50);
        Thread t2 = new Thread() {
            @Override
            public void run() {
                try {
                    //semaphore.acquire();
                    //不被interrupt()中断
                    semaphore.acquireUninterruptibly();
                    TimeUnit.SECONDS.sleep(4);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
                System.out.println("t2 finished");

            }
        };
        t2.start();
        t2.interrupt();
    }
}
